#pragma once

#include <string>
#include <cstdio>
#include <errno.h>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

class Sock
{
private:
    const static int gbacklog = 20;

public:

    // 创建套接字，返回sockfd
    static int Socket()
    {
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if (sock < 0)
        {
            Messagelog(FATAL, "creat socket error:%d-%s", errno, strerror(errno));
            exit(2);
        }
        int opt = 1;
        setsockopt(sock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        Messagelog(NORMAL, "socket creat success :%d", sock);
        return sock;
    }
    // sock port (ip)
    static void Bind(int sock, uint16_t port, const std::string &ip = "")
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = ip.empty() ? INADDR_ANY : inet_addr(ip.c_str());
        socklen_t len = sizeof(local);
        if (bind(sock, (struct sockaddr *)&local, len) < 0)
        {
            Messagelog(FATAL, "bind error:%d-%s", errno, strerror(errno));
            exit(3);
        }
        Messagelog(NORMAL, "socket bind success");
    }

    static void Listen(int sock)
    {
        if (listen(sock, gbacklog) < 0)
        {
            Messagelog(FATAL, "listen error:%d-%s", errno, strerror(errno));
            exit(4);
        }
        Messagelog(NORMAL, "listen... ");
    }

    // 输出型参数
    static int Accept(int sock, std::string* cli_ip, uint16_t* cli_port)
    {
        struct sockaddr_in src;
        socklen_t len = sizeof(src);
        int fd = accept(sock, (struct sockaddr *)&src, &len);
        if (fd < 0)
        {
            Messagelog(ERROR, "connect fail:%d-%s", errno, strerror(errno));
            return fd;
        }
        std::string src_ip = inet_ntoa(src.sin_addr);
        uint16_t src_port = ntohs(src.sin_port);
        if(cli_ip) *cli_ip = src_ip;
        if(cli_port) *cli_port = src_port;

        Messagelog(NORMAL, "connect:[ %s | %d ]", src_ip.c_str(), src_port);
        return fd;
    }

    static bool Connect(int sock, const std::string& ip, uint16_t port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = ntohs(port);
        server.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof(server);

        if(connect(sock, (struct sockaddr*)&server, len) < 0)
        {
            Messagelog(ERROR, "connect error %d-%s", errno, strerror(errno));
            return false;
        }
        Messagelog(NORMAL, "connect success");
        return true;
    }

};
